package org.yi.web.account.entity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.yi.core.annotation.TableBind;
import org.yi.core.exceptions.NotUniqueResultException;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

@TableBind(name = "f_account")
public class AccountEntity extends Model<AccountEntity>{
	
	private static final long serialVersionUID = -4368208647272740379L;
	
	private static final String TABLE_NAME = "f_account";
	
	public static final AccountEntity dao = new AccountEntity();
	
	/**
	 * get account by loginname and password
	 * @param loginname
	 * @param pw
	 * @return
	 */
	public List<AccountEntity> list(String loginname, String pw){
		String sql = "select * from " + TABLE_NAME + " where login_name = ? and passwd = ?";
		List<AccountEntity> list = dao.find(sql, loginname, pw);
		return list;
	}
	
	/**
	 * 根据邮箱和密码获取用户
	 * @param username
	 * @param pw
	 * @return
	 * @throws NotUniqueResultException 
	 */
	public AccountEntity getByNamePwd(String loginname, String pw) {
		String sql = "select * from " + TABLE_NAME + " where login_name = ? and passwd = ?";
		return findFirst(sql,loginname);
	}
	
	/**
	 * 判断用户是否存在， 存在返回true， 否则返回false
	 * @param loginname
	 * @return
	 */
	public boolean userExist(String loginname) {
		String sql = "select count(*) from " + TABLE_NAME + " where login_name = ?";
		return Db.queryLong(sql, loginname) > 0;
	}
	
	/**
	 * 根据用户名获取用户
	 * @param username
	 * @return
	 */
	public AccountEntity getByName(String loginname){
		String sql = "select * from " + TABLE_NAME + " where login_name = ?";
		return findFirst(sql,loginname);
	}

	public Object getIdTitleMap() {
		Map<Long, String> map = new HashMap<Long, String>();
		String sql = "select * from f_account";
		List<AccountEntity> list = dao.find(sql);
		for(AccountEntity a: list) {
			map.put(a.getLong("id"), a.getStr("login_name"));
		}
		return map;
	}

}
